<?php
$url = "http://localhost/xml/utf8.xml";
$url = "http://localhost/xml/gbk.xml";
/**
 * 不论什么编码,读到字符串都是以utf-8字符编码存储到字符串
 *  gbk.xml gbk文件 以utf-8字符编码读取到字符串 字符串是已经乱码,字符中声明GBK编码,simplexml_load_string()可以解析
 *  utf8.xml utf-8 文件 以utf-8字符编码读取到字符串 字符串正常,字符中声明UTF-8编码,simplexml_load_string()可以解析
 */
$xml = Xml::readFile($url);
Xml::getEncoding($xml);
Xml::xml2Arr($xml);

/**
 * gbk声明的字符串 以utf-8编码读取字符串 字符串是已经乱码
 * 任然可以解析成正常数据
 */
/*echo "</hr>\n";
$xml = Xml::readFile($url2);
Xml::getEncoding($xml);
Xml::xml2Arr($xml);*/


/**
 * 使用utf-8编码的字符串,但是申明是GBK
 * 解析报错 simplexml_load_string(): input conversion failed due to input error
 * 方案 1 将xml中的encodeing 替换为UTF-8
 * 方案 2 将xml 编码转化为xml声明声明的编码
 */
$xml = <<<EOF
<?xml version="1.0" encoding="GBK"?>
<paq>
    <paq_body>
        <HolderIdentify>
            <Flag>FALSE</Flag>
            <Message>FALSE&amp;文件是GBK编码,声明编码GBK !!</Message>
            <Email />
            <Name>胡歌李</Name>
            <Sex>Male</Sex>
            <Birthday>1991-10-28</Birthday>
            <DocumentType>A</DocumentType>
            <DocumentID />
            <Mobile>18518488785</Mobile>
        </HolderIdentify>
    </paq_body>
</paq>
EOF;

Xml::getEncoding($xml);
//方案 1 替换声明的字符为UTF-8
//$xml = str_replace('encoding="GBK"', 'encoding="UTF-8"', $xml);

//方案 2 将UTF-8字符串转换为声明的字符集GBK
//$xml = iconv("utf-8", "GBK", $xml);
//$xml = Xml::conv($xml,"GBK","utf-8");
//Xml::xml2Arr($xml);



class Xml
{
    static function readFile($url)
    {
        $xml = file_get_contents($url);
        $xml = trim($xml, "\t\n\r");
        return $xml;
    }

    static function getEncoding($xml)
    {
        $encodeName = mb_detect_encoding($xml);
        var_dump($encodeName);
        return $encodeName;
    }

    static function xml2Arr($xml)
    {
        $xml = trim($xml, "\t\n\r");
        $data = simplexml_load_string($xml);
        $data = json_decode(json_encode($data), true);
        var_dump($xml, $data);
    }

    static function conv($xml, $to, $from)
    {
        return mb_convert_encoding($xml, $to, $from);
    }
}